package com.mini.service;

import com.google.common.collect.Lists;
import com.mini.client.MiniAdminClient;
import com.mini.constant.RedisKeyConst;
import com.mini.vo.BusinessResult;
import com.mini.vo.DeptVO;
import com.mini.vo.FullDeptVo;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author zl
 * @version 1.0
 * @date Created in 2020/2/6
 */
@Service
@Slf4j
public class MiniAdminService {

    @Value("${mini.eureka.call.sign}")
    private String reqSign;

    @Autowired
    private MiniAdminClient mnsClient;

    @Autowired
    protected RedisTemplate redisTemplate;


    /**
     * 按组织查询从当前组织到顶级所有的角色化组织
     *
     * @param deptId
     * @return
     */
    public FullDeptVo findFullDept(Long deptId) {
        if (Objects.isNull(deptId)) {
            return null;
        }

        String key = RedisKeyConst.getFullDeptVo(deptId);
        FullDeptVo fullDeptVo = (FullDeptVo) redisTemplate.opsForValue().get(key);
        if (Objects.nonNull(fullDeptVo)) {
            return fullDeptVo;
        }

        BusinessResult<FullDeptVo> result = mnsClient.findFullDept(reqSign, deptId);
        fullDeptVo = result.getData();
        if (Objects.nonNull(fullDeptVo)) {
            redisTemplate.opsForValue().set(key, fullDeptVo, 2, TimeUnit.MINUTES);
        }
        return fullDeptVo;
    }

    /**
     * 当前组织名称
     *
     * @param deptId
     * @return
     */
    public String getDeptName(Long deptId) {
        FullDeptVo fullDeptVo = findFullDept(deptId);
        if (Objects.nonNull(fullDeptVo)) {
            return fullDeptVo.getDeptName();
        }

        return null;
    }

    /**
     * 从顶级到当前组织名称拼接
     *
     * @param deptId
     * @return
     */
    public String getDeptFullName(Long deptId) {
        FullDeptVo fullDeptVo = findFullDept(deptId);
        if (Objects.nonNull(fullDeptVo)) {
            return fullDeptVo.getDeptFullName();
        }

        return null;
    }

    /**
     * 获取运营组以及运营部名称
     *
     * @param id
     * @return
     */
    public String getOrgGroupName(Long id) {
        StringBuffer sb = new StringBuffer();
        FullDeptVo fullDeptVo = findFullDept(id);
        if (Objects.nonNull(fullDeptVo)) {
            if (StringUtils.isNotBlank(fullDeptVo.getOdName())) {
                sb.append(fullDeptVo.getOdName()).append("-").append(fullDeptVo.getOgName());
            } else {
                sb.append(fullDeptVo.getOgName());
            }
        }
        return sb.toString();
    }

    /**
     * 查询儿子组织
     *
     * @param deptId
     * @return
     */
    public List<DeptVO> getSonDeptList(Long deptId) {
        if (Objects.isNull(deptId)) {
            return new ArrayList<>();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.getSonDeptList(reqSign, deptId);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }

    /**
     * 查询父组织
     *
     * @param deptId
     * @return
     */
    public DeptVO getParentDept(Long deptId) {
        if (Objects.isNull(deptId)) {
            return null;
        }
        BusinessResult<DeptVO> result = mnsClient.getParentDept(reqSign, deptId);
        return result.getData();
    }

    /**
     * 查询当前组织任意级别的直系亲属组织
     *
     * @param deptId
     * @param level
     * @return
     */
    public List<DeptVO> getDirectRelativeDepts(Long deptId, Integer level) {
        if (Objects.isNull(deptId) || Objects.isNull(level)) {
            return new ArrayList<>();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.getDirectRelativeDepts(reqSign, deptId, level);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }

    /**
     * 按组织和级别查询当前组织下的某一级别组织列表
     *
     * @param deptId
     * @param level
     * @return
     */
    public List<DeptVO> findChildDepts(Long deptId, Integer level) {
        if (Objects.isNull(deptId) || Objects.isNull(level)) {
            return new ArrayList<>();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.findChildDepts(reqSign, deptId, level);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }

    /**
     * 批量查询组织信息
     *
     * @param deptIds
     * @return
     */
    public List<DeptVO> getDeptsBatch(Set<Long> deptIds) {
        if (CollectionUtils.isEmpty(deptIds)) {
            return new ArrayList<>();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.getDeptsBatch(reqSign, deptIds);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }


    /**
     * 查询用户简版信息，包括用户所在组织到顶级所有的角色化组织
     *
     * @param userId
     * @return
     */
    public UserVO getUserSimpleInfo(Long userId) {
        if (Objects.isNull(userId)) {
            return null;
        }

        try {
            String key = RedisKeyConst.getUserSimpleInfoKey(userId);

            UserVO userVO = (UserVO) redisTemplate.opsForValue().get(key);
            if (Objects.nonNull(userVO)) {
                return userVO;
            }

            BusinessResult<UserVO> result = mnsClient.getUserSimpleInfo(reqSign, userId);
            userVO = result.getData();
            if (Objects.nonNull(userVO)) {
                redisTemplate.opsForValue().set(key, userVO, 2, TimeUnit.MINUTES);
            }
            return userVO;
        } catch (Exception e) {
            log.error("查询用户基本信息异常，userId={}", userId, e);
        }

        return null;
    }

    /**
     * 批量查询用户简版信息
     *
     * @param userIds
     * @return
     */
    public List<UserVO> batchFindUserList(Set<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Lists.newArrayList();
        }
        BusinessResult<List<UserVO>> result = mnsClient.batchFindUserList(reqSign, userIds);
        if (CollectionUtils.isEmpty(result.getData())) {
            return Lists.newArrayList();
        }
        return result.getData();
    }


    /**
     * 查询用户昵称
     *
     * @param userId
     * @return
     */
    public String getUserNickName(Long userId) {
        UserVO user = getUserSimpleInfo(userId);
        if (Objects.isNull(user)) {
            return null;
        }
        return user.getNickname();
    }

    /**
     * 用户所在组织到顶级所有的角色化组织
     *
     * @param userId
     * @return
     */
    public FullDeptVo getUserFullDept(Long userId) {
        UserVO user = getUserSimpleInfo(userId);
        if (Objects.isNull(user)) {
            return null;
        }
        return user.getFullDept();
    }


    /**
     * 查询用户从顶级到用户所在组织名称拼接
     *
     * @param userId
     * @return
     */
    public String getUserDeptFullName(Long userId) {
        FullDeptVo fullDeptVo = getUserFullDept(userId);
        if (Objects.isNull(fullDeptVo)) {
            return null;
        }

        return fullDeptVo.getDeptFullName();
    }

    /**
     * 查询用户所在的组织名称
     *
     * @param userId
     * @return
     */
    public String getUserDeptName(Long userId) {
        FullDeptVo fullDeptVo = getUserFullDept(userId);
        if (Objects.isNull(fullDeptVo)) {
            return null;
        }

        return fullDeptVo.getDeptName();
    }

    /**
     * 获取登录用户信息
     *
     * @param token
     * @return
     */
    public UserVO getLoginUser(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        try {
            BusinessResult<UserVO> result = mnsClient.checkLogin(token);
            return result.getData();
        } catch (Exception e) {
            log.warn("getLoginUser 未登录{}", token);
        }
        return null;
    }

    /**
     * 用户是否登录
     *
     * @param token
     * @return
     */
    public Boolean isLogin(String token) {
        UserVO userVO = getLoginUser(token);
        return Objects.nonNull(userVO);
    }

    /**
     * 用户id
     *
     * @param token
     * @return
     */
    public Long getLoginUserId(String token) {
        UserVO userVO = getLoginUser(token);
        return Objects.isNull(userVO) ? null : userVO.getId();
    }

    public Set<String> getPermission(String token) {
        UserVO userVo = getLoginUser(token);
        if (Objects.isNull(userVo)) {
            return null;
        }
        return userVo.getRoles();
    }

    /**
     * 权限范围内的 项目专员
     *
     * @param userId
     * @return
     */
    public List<Long> scopedAdvertisingUserIds(Long userId) {
        if (Objects.isNull(userId)) {
            return new ArrayList<>();
        }
        BusinessResult<List<Long>> result = mnsClient.scopedAdvertisingUserIds(reqSign, userId);
        return result.getData();
    }

    /**
     * 权限范围内运营专员/咨询师基础信息
     *
     * @param token
     * @return
     */
    public List<UserVO> scopedOperationUserList(String token) {
        if (Objects.isNull(token)) {
            return new ArrayList<>();
        }
        BusinessResult<List<UserVO>> result = mnsClient.scopedOperationUserList(token);
        return result.getData();
    }


    /**
     * 权限范围内运营专员(咨询师)/组长
     *
     * @param userId
     * @return
     */
    public List<Long> scopedOperationUserIds(Long userId) {
        if (Objects.isNull(userId)) {
            return new ArrayList<>();
        }
        BusinessResult<List<Long>> result = mnsClient.scopedOperationUserIds(reqSign, userId);
        return result.getData();
    }

    /**
     * 权限范围内运营专员(咨询师)/组长，包括历史接线
     *
     * @param userId
     * @return
     */
    public List<Long> scopedOperationUserIdsHistory(Long userId) {
        if (Objects.isNull(userId)) {
            return new ArrayList<>();
        }
        BusinessResult<List<Long>> result = mnsClient.scopedOperationUserIdsHistory(reqSign, userId);
        return result.getData();
    }

    /**
     * 根据登录人权限查看运营工作室(量子军团)集合
     *
     * @param token
     * @return
     */
    public List<DeptVO> getWorkRoomDeptList(String token) {
        if (StringUtils.isBlank(token)) {
            return new ArrayList<>();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.getWorkRoomDeptList(token);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }

    /**
     * 根据登录人权限查看登录人可以查看的运营工作室(量子军团)集合
     *
     * @param token
     * @return
     */
    public List<DeptVO> getChildWorkRoomDeptList(String token) {
        if (StringUtils.isBlank(token)) {
            return new ArrayList<>();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.getChildWorkRoomDeptList(token);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }

    /**
     * 根据任意组织查用户权限范围内的运营组
     *
     * @param deptIds
     * @param userId
     * @return
     */
    public List<DeptVO> findGroupInfos(Set<Long> deptIds, Long userId) {
        if (CollectionUtils.isEmpty(deptIds) || Objects.isNull(userId)) {
            return Lists.newArrayList();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.findOperatDepts(reqSign, deptIds, userId);
        if (CollectionUtils.isEmpty(result.getData())) {
            return Lists.newArrayList();
        }
        return result.getData();
    }

    /**
     * 按任意组织查询登录用户权限范围内的运营专员(咨询师)/组长简版信息列表
     *
     * @param token
     * @param deptIds
     * @return
     */
    public List<UserVO> operationUserFilter(String token, Set<Long> deptIds) {
        if (CollectionUtils.isEmpty(deptIds) || StringUtils.isBlank(token)) {
            return Lists.newArrayList();
        }

        BusinessResult<List<UserVO>> result = mnsClient.operationUserFilter(token, deptIds);

        if (CollectionUtils.isEmpty(result.getData())) {
            return Lists.newArrayList();
        }
        return result.getData();

    }

    /**
     * 按任意组织查询登录用户权限范围内的正在接线的运营专员(咨询师)/组长简版信息列表
     *
     * @param token
     * @param deptIds
     * @return
     */
    public List<UserVO> operationUserFilterValid(String token, Set<Long> deptIds) {
        if (CollectionUtils.isEmpty(deptIds) || StringUtils.isBlank(token)) {
            return Lists.newArrayList();
        }

        BusinessResult<List<UserVO>> result = mnsClient.operationUserFilterValid(token, deptIds);

        if (CollectionUtils.isEmpty(result.getData())) {
            return Lists.newArrayList();
        }
        return result.getData();

    }

    /**
     * 权限范围内的投放工作室
     *
     * @param token
     * @return
     */
    public List<DeptVO> advertisingDepts(String token) {
        if (StringUtils.isBlank(token)) {
            return Lists.newArrayList();
        }
        BusinessResult<List<DeptVO>> result = mnsClient.advertisingDepts(token);
        if (CollectionUtils.isEmpty(result.getData())) {
            return Lists.newArrayList();
        }
        return result.getData();
    }

    /**
     * 根据登录人权限查看运营工作室(量子军团)集合
     *
     * @param token
     * @return
     */
    public List<Long> scopedSOPUserIds(String token) {
        if (StringUtils.isBlank(token)) {
            return new ArrayList<>();
        }
        BusinessResult<List<Long>> result = mnsClient.scopedSOPUserIds(token);
        if (CollectionUtils.isEmpty(result.getData())) {
            return new ArrayList<>();
        }
        return result.getData();
    }


}

